﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Text;

namespace SweetSQL.Data.Providers
{
    internal abstract class ConnectionProviderBase : IConnectionProvider
    {
        public ConnectionProviderBase(ConnectionParameters parameters)
        {
            Parameters = parameters;
        }

        #region ISqlProvider Members

        public ConnectionParameters Parameters
        {
            get;
            private set;
        }

        public int CommandTimeout
        {
            get { return Parameters.CommandTimeout; }
        }

        public bool Connected
        {
            get;
            protected set;
        }

        public IDbConnection Connection
        {
            get;
            protected set;
        }

        public IDbTransaction Transaction
        {
            get;
            protected set;
        }

        public virtual void Connect() { }

        public virtual void BeginTransaction()
        {
            Transaction = Connection.BeginTransaction();
        }

        public virtual void Commit()
        {
            if (Transaction != null)
            {
                Transaction.Commit();
                Transaction.Dispose();
                Transaction = null;
            }
        }

        public virtual void Rollback()
        {
            if (Transaction != null)
            {
                Transaction.Rollback();
                Transaction.Dispose();
                Transaction = null;
            }
        }

        public virtual IDbCommand CreateCommand(string sql)
        {
            throw new NotImplementedException();
        }

        public virtual IDataParameter CreateParameter(string name, Type type, int index)
        {
            throw new NotImplementedException();
        }

        public virtual void SetParameter(ColumnInfo columnInfo) { }

        public virtual object ConvertToDatabase(Type type, object value)
        {
            return value;
        }

        public virtual object ConvertToClr(Type type, object value)
        {
            return Util.DefaultConvert(type, value);
        }

        public virtual void Dispose()
        {
            if (Transaction != null)
            {
                Transaction.Dispose();
                Transaction = null;
            }
            if (Connection != null)
            {
                Connection.Dispose();
                Connection = null;
            }
        }

        #endregion
    }
}
